package getools4me;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;

/**
 * this servlet just do the jobs on start up
 * 
 * @author Evan
 * 
 */
public class LoadOnStartUpServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = -4516336881719964412L;

	@Override
	/**
	 * do some compile jobs: compile utils project to a jar file and add it to web lib
	 */
	public void init(ServletConfig config) throws ServletException {
		
		File dir = new File("");
		String contextPath = getParentPath(dir.getAbsolutePath());
		String projectPath = getParentPath(contextPath,2);
		File _ant2 = new File(contextPath,"_ant2.bat");
		
		if(!_ant2.exists()){
			System.err.print("File not found: "+_ant2.getAbsolutePath());
			return;
		}else{
			System.out.println("File located: "+_ant2.getAbsolutePath());
		}
		
		// set the environment
		String JAVA_HOME = getChildPath(projectPath, "tools", "eclipseHeliosEE", "jdk");
		String PATH = getChildPath(JAVA_HOME, "bin");
		String ant = getChildPath(projectPath, "tools", "apache-ant-1.8.2", "bin","ant.bat");
		String buildfile = getChildPath(contextPath, "build.xml");
		String target = "do";
		
		// read the file
		String fileContent = null;
		try {
			FileInputStream fis = new FileInputStream(_ant2);
			int size = (int) _ant2.length();
			byte[] b = new byte[size];
			fis.read(b);
			fis.close();
			fileContent = new String(b);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		// replace the variable
		fileContent = fileContent.replace("${JAVA_HOME}", JAVA_HOME);
		fileContent = fileContent.replace("${PATH}", PATH);
		fileContent = fileContent.replace("${ant}", ant);
		fileContent = fileContent.replace("${buildfile}", buildfile);
		fileContent = fileContent.replace("${target}", target);
		System.out.println(fileContent);
		
		// run the command
		jar(fileContent);
		
	}

	
	
	public static String getChildPath(String parentPath, String... childName){
		String path = parentPath;
		for(String cn : childName){
			path = getChildPath(path, cn);
		}
		return path;
	}
	
	
	public static String getChildPath(String parentPath, String childName){
		if(parentPath.indexOf("/")!=-1){
			String path = parentPath.trim()+"/"+childName.trim();
			while(path.indexOf("//")!=-1){
				path = path.replace("//", "/");
			}
			return path;
		}
		if(parentPath.indexOf("\\")!=-1){
			String path = parentPath.trim()+"\\"+childName.trim();
			while(path.indexOf("\\\\")!=-1){
				path = path.replace("\\\\", "\\");
			}
			return path;
		}
		String path = parentPath.trim()+"/"+childName.trim();
		while(path.indexOf("//")!=-1){
			path = path.replace("//", "/");
		}
		return path;
		
		
	}
	public static String getParentPath(String path,int level){
		String parentPath = path;
		for(int i=0;i<level;i++){
			parentPath = getParentPath(parentPath);
		}
		return parentPath;
	}
	
	public static String getParentPath(String path){
		if(path.indexOf("/")==-1 && path.indexOf("\\")==-1) return null;
		return path.indexOf("/")!=-1?path.substring(0, path.lastIndexOf("/")):path.substring(0, path.lastIndexOf("\\"));
	}
	
	
	public static void jar(String cmdString) {
		
		try {
			Process p = Runtime.getRuntime().exec("cmd");

			// input the command
			PrintStream ps = new PrintStream(p.getOutputStream());
			ps.println(cmdString);
			ps.flush();
			ps.close();
			
			// normal output
			InputStream is = p.getInputStream();
			byte[] b = new byte[1024];
			int size = -1;
			while ((size = is.read(b)) != -1) {
				System.out.println(new String(b, 0, size));
			}

			// error output
			is = p.getErrorStream();
			b = new byte[1024];
			size = -1;
			while ((size = is.read(b)) != -1) {
				System.err.println(new String(b, 0, size));
			}

			System.out.print("Exit Code:");
			System.out.println(p.exitValue());

		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
